//
//  HKCalendarView.m
//  HKProject
//
//  Created by 胡锦涛 on 2018/8/15.
//  Copyright © 2018年 胡锦涛. All rights reserved.
//

#import "HKCalendarView.h"
#import <HKLibCommon/HKPrefixHeader.h>
@interface HKCalendarView()

@property (nonatomic, weak) UIButton *preBtn;
@property (nonatomic, weak) UIButton *nextBtn;

@property (nonatomic, weak) UILabel *titleLabel;
@property (nonatomic, weak) UIView *titleView;
@property (nonatomic, weak) UIView *dateView;

@property (nonatomic, strong) NSMutableArray *dateArray;
@property (nonatomic, strong) NSMutableArray *labelArray;
@property (nonatomic, strong) NSMutableArray *buttonArray;

@property (nonatomic, assign) NSInteger days;
@property (nonatomic, assign) NSInteger firstDays;

@property (nonatomic, strong) NSDate *currentDate;

@property (nonatomic, strong) NSString * resultDate;
@end

@implementation HKCalendarView
- (NSMutableArray *)buttonArray {
    if (!_buttonArray) {
        
        _buttonArray = [NSMutableArray array];
    }
    return _buttonArray;
}

- (NSMutableArray *)labelArray {
    if (!_labelArray) {
        _labelArray = [NSMutableArray array];
    }
    return _labelArray;
}

- (NSMutableArray *)dateArray {
    if (!_dateArray) {
        
        _dateArray = [NSMutableArray arrayWithObjects:@"日",@"一",@"二",@"三",@"四",@"五",@"六", nil];
    }
    return _dateArray;
}

// 获取日
- (NSInteger)getCurrentDay:(NSDate *)date {
    
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *components = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:date];
    
    NSInteger day = [components day];
    return day;
}

// 获取月
- (NSInteger)getCurrentMonth:(NSDate *)date {
    
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *components = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:date];
    
    NSInteger month = [components month];
    return month;
}

// 获取年
- (NSInteger)getCurrentYear:(NSDate *)date {
    
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *components = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:date];
    
    NSInteger year = [components year];
    return year;
}

// 一个月有多少天
- (NSInteger)getTotalDaysInMonth:(NSDate *)date {
    
    NSRange daysInOfMonth = [[NSCalendar currentCalendar] rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:date];
    return daysInOfMonth.length;
}

// 每月第一天
- (NSInteger)getFirstDayOfMonth:(NSDate *)date {
    
    NSInteger firstDayOfMonth = [[NSCalendar currentCalendar] ordinalityOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitWeekOfMonth forDate:date];
    return firstDayOfMonth;
}

// 上个月
- (NSDate *)lastMonth:(NSDate *)date {
    NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
    dateComponents.month = -1;
    NSDate *newDate = [[NSCalendar currentCalendar] dateByAddingComponents:dateComponents toDate:date options:0];
    return newDate;
}

// 下个月
- (NSDate *)nextMonth:(NSDate *)date {
    NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
    dateComponents.month = +1;
    NSDate *newDate = [[NSCalendar currentCalendar] dateByAddingComponents:dateComponents toDate:date options:0];
    return newDate;
}

+(HKCalendarView *)initWithFrame:(CGRect)frame andSelectedDate:(NSDate *)date {
    HKCalendarView *view = [[HKCalendarView alloc] initWithFrame:frame];
    view.preselectedDate = date;
    [view loadWithDate:view.currentDate];
    return view;
}
- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        
        self.backgroundColor = [UIColor whiteColor];// Color(244, 244, 244);
        
        _currentDate = [NSDate date];
        
        UIButton *preBtn = [[UIButton alloc] init];
        //[preBtn setTitle:@"<<" forState:UIControlStateNormal];
        [preBtn setTitle:@"上个月" forState:UIControlStateNormal];
        [preBtn.titleLabel setFont:HKFont(15)];
        [preBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [preBtn addTarget:self action:@selector(preBtnClick) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:preBtn];
        self.preBtn = preBtn;
        
        UIButton *nextBtn = [[UIButton alloc] init];
        //[nextBtn setTitle:@">>" forState:UIControlStateNormal];
        [nextBtn setTitle:@"下个月" forState:UIControlStateNormal];
        [nextBtn.titleLabel setFont:HKFont(15)];
        [nextBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [nextBtn addTarget:self action:@selector(nextBtnClick) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:nextBtn];
        self.nextBtn = nextBtn;
        
        UILabel *titleLable = [[UILabel alloc] init];
        titleLable.text = @"2010年10月20日";
        titleLable.textAlignment = NSTextAlignmentCenter;
        titleLable.textColor = [UIColor blackColor];
        [self addSubview:titleLable];
        self.titleLabel = titleLable;
        
        
        UIView *titleView = [[UIView alloc] init];
        titleView.backgroundColor = [UIColor clearColor];
        [self addSubview:titleView];
        self.titleView = titleView;
        
        for (int i = 0; i < self.dateArray.count; i++) {
            
            UILabel *label = [[UILabel alloc] init];
            label.text = self.dateArray[i];
            label.textColor = HKRGB(0, 176, 160);
            label.textAlignment = NSTextAlignmentCenter;
            [self.titleView addSubview:label];
            [self.labelArray addObject:label];
        }
        
        UIView *dateView = [[UIView alloc] init];
        dateView.backgroundColor = [UIColor clearColor];
        [self addSubview:dateView];
        self.dateView = dateView;
        
    }
    return self;
}

- (void)loadWithDate:(NSDate *)date {
    
    // 移除所有
    if (self.buttonArray) {
        [self.buttonArray removeAllObjects];
    }
    
    if (self.dateView.subviews.count > 0) {
        [self.dateView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    }
    
    // 获取当月有多少天
    _days = [self getTotalDaysInMonth:date];
    _firstDays = [self getFirstDayOfMonth:date];
    
    //self.titleLable.text = [NSString stringWithFormat:@"%zd年%zd月%zd日",[self getCurrentYear:date],[self getCurrentMonth:date],[self getCurrentDay:date]];
    self.titleLabel.text = [NSString stringWithFormat:@"%zd年%zd月",[self getCurrentYear:date],[self getCurrentMonth:date]];
    
    for (int i = 1; i <= _days; i++) {
        UIButton *button = [[UIButton alloc] init];
        [button setTitle:[NSString stringWithFormat:@"%d",i] forState:UIControlStateNormal];
        [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        button.layer.cornerRadius = 5;
        if (i == [self getCurrentDay:_preselectedDate]) {
            button.backgroundColor = HKRGB(0, 176, 160);
            [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            
        }
        [self.dateView addSubview:button];
        [self.buttonArray addObject:button];
        
        // 更新选中的文字
        self.currentString = [NSString stringWithFormat:@"%ld-%02ld", (long)[self getCurrentYear:date],(long)[self getCurrentMonth:date]];
        
        
        button.tag = i;
        [button addTarget:self action:@selector(showToday:) forControlEvents:UIControlEventTouchUpInside];
    }
}

- (void)showToday: (UIButton *)sender{
    // 先清除所有的图片
    for (UIButton *button in self.dateView.subviews) {
        if ([button isKindOfClass:[UIButton class]]) {
            [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
            button.backgroundColor = [UIColor whiteColor];
            [button hk_removeShadow];
        }
    }
    sender.backgroundColor = HKRGB(0, 176, 160);
    [sender setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    sender.layer.cornerRadius = 5;
    
    // 更新选中的文字
    self.resultDate = [self.currentString stringByAppendingString:[NSString stringWithFormat:@"-%02ld", (long)sender.tag]];
    
    if (self.selectBlock) {
        self.selectBlock(self.resultDate);
    }
}


- (void)preBtnClick {
    
    NSDate *preDate = [self lastMonth:_currentDate];
    [self loadWithDate:preDate];
    
    [self setNeedsLayout];
    
    _currentDate = preDate;
    
}

- (void)nextBtnClick {
    
    NSDate *nextDate = [self nextMonth:_currentDate];
    [self loadWithDate:nextDate];
    
    [self setNeedsLayout];
    
    _currentDate = nextDate;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    
    self.titleLabel.frame = CGRectMake(0, 0, self.hk_width, 40);
    
    self.preBtn.hk_size = CGSizeMake(60, 40);
    self.preBtn.hk_x = 5;
    self.preBtn.hk_y = 0;
    
    self.nextBtn.hk_size = CGSizeMake(60, 40);
    self.nextBtn.hk_y = 0;
    self.nextBtn.hk_x = self.hk_width - self.nextBtn.hk_width - 0;
    
    
    self.titleView.frame = CGRectMake(0, self.titleLabel.hk_bottom, self.hk_width, 40);
    
    for (int i = 0; i < self.labelArray.count; i++) {
        UILabel *label = self.labelArray[i];
        label.hk_width = self.hk_width / 7;
        label.hk_height = self.titleView.hk_height;
        label.hk_y = 0;
        label.hk_x = i * label.hk_width;
        
    }
    
    self.dateView.frame = CGRectMake(0, self.titleView.hk_bottom, self.hk_width,  self.hk_height - self.titleView.hk_bottom);
    
    // 计算有多少行
    NSInteger row = (_firstDays % 7 + _days + 6) / 7;
    
    NSInteger colum = 7;
    CGFloat buttonH = self.dateView.hk_height / row;
    CGFloat buttonW = self.dateView.hk_width / 7;
    
    for (int i = 0; i < self.buttonArray.count; i++) {
        UIButton *button = self.buttonArray[i];
        button.hk_width = buttonW;
        button.hk_height = buttonH;
        button.hk_x = (_firstDays % 7 + i) % colum * buttonW;
        button.hk_y = (_firstDays % 7 + i) / colum * buttonH;
        
    }
    
}

- (void)selectDate: (void (^)(NSString *selectDateString))selectBlock{
    self.selectBlock = selectBlock;
}
-(void)show
{
    
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    [window addSubview: self];
    [window bringSubviewToFront: self];
    
    self.alpha = 0;
    [self setHidden: NO];
    self.transform = CGAffineTransformMakeScale(0, 0);
    [UIView animateWithDuration:0.6 delay:0 usingSpringWithDamping:0.7 initialSpringVelocity:0.8 options:UIViewAnimationOptionTransitionFlipFromBottom animations:^{
        self.transform = CGAffineTransformIdentity;
        self.alpha = 1.0;
    } completion:^(BOOL finished) {
        
    }];
}
-(void)hidden
{
    [UIView animateWithDuration:0.6 delay:0 usingSpringWithDamping:0.7 initialSpringVelocity: 0.2
                        options:UIViewAnimationOptionCurveEaseInOut animations:^{
                            self.alpha = 0.0;
                        } completion:^(BOOL finished) {
                            [self removeFromSuperview];
                        }];
    
}
@end
